<?php

namespace Aoe\Emulator;

use Aoe\Attributes\Container\Argument;
use Aoe\Core\Module;
use Aoe\Emulator\Schema\Models;
use SplObjectStorage;

/**
 * # AoeSchema 对外接口
 *  * 由Kernel管理
 */
class Smart
{
    const string KEY = 'schema';

    const string ELEMENTS_KEY = 'elements';
    
    /**
     * @var SplObjectStorage<Module, Models>
     */
    protected SplObjectStorage $centers;

    /**
     * @param array $pre_elements 元素预定义
     */
    public function __construct(
        #[Argument(self::ELEMENTS_KEY)] private readonly array $pre_elements = [],
    ) {
        $this->centers = new SplObjectStorage();
    }
    
    public function getModelsOf(Module $module): Models
    {
        if (!isset($this->centers[$module])) {
            $this->centers[$module] = new Models($module->schema, $this, $module->name);
        }
        return $this->centers[$module];
    }

    /**
     * 混合元素预置的属性
     *
     * @param array $defs
     *
     * @return array
     */
    public function mixinElementPreset(array $defs): array
    {
        $key = $defs[self::KEY] ?? false;
        if (!$key) return $defs;
        
        $preset = $this->pre_elements[$key] ?? false;
        if (!$preset) return $defs;
        
        //自定义属性优先
        $r = array_merge($preset, $defs);
        unset($r[$key]);

        return $r;
        
    }
}